package com.example.gui;

import com.example.dao.AdminDAO;
import com.example.model.Deposit;
import com.example.model.TradeInfo;
import com.example.util.DepositTableModel;
import com.example.util.TradeInfoTableModel;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdesktop.swingx.JXDatePicker;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class TransactionManagementPanel extends JPanel {

    static AdminDAO adminDAO = new AdminDAO();

    TradeInfoTableModel tableModel;
    JTable tradeInfoTable;
    List<TradeInfo> tradeInfoData;

    TradeInfoFind tradeInfoFind = new TradeInfoFind();

    public TransactionManagementPanel() {

        tradeInfoData = fetchTradeInfoData();
        tableModel = new TradeInfoTableModel(tradeInfoData);
        tradeInfoTable = new JTable(tableModel);

        // 设置表格外观
        tradeInfoTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        tradeInfoTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        tradeInfoTable.setRowHeight(30);
        tradeInfoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("交易记录查询", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        add(titleLabel, BorderLayout.NORTH);

        // 查询条件面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        filterPanel.setBorder(BorderFactory.createTitledBorder("查询条件"));

        filterPanel.add(new JLabel("交易类型:"));
        JComboBox<String> typeCombo = new JComboBox<>(new String[]{"全部", "存款", "取款", "转账"});
        filterPanel.add(typeCombo);

        filterPanel.add(new JLabel("客户ID:"));
        JTextField customerName = new JTextField(10);
        filterPanel.add(customerName);

        filterPanel.add(new JLabel("交易日期:"));
        // 创建日期选择器

        JXDatePicker datePicker1 = new JXDatePicker();
        datePicker1.setDate(new Date()); // 设置默认日期为今天
        datePicker1.setFormats("yyyy-MM-dd"); // 设置日期格式
        JXDatePicker datePicker2 = new JXDatePicker();
        datePicker2.setDate(new Date()); // 设置默认日期为今天
        datePicker2.setFormats("yyyy-MM-dd"); // 设置日期格式

        filterPanel.add(new JLabel("开始:"));
        filterPanel.add(datePicker1);
        filterPanel.add(new JLabel("截至:"));
        filterPanel.add(datePicker2);

        JButton queryBtn = new JButton("查询");
        queryBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        queryBtn.setBackground(new Color(70, 130, 180));
        queryBtn.setForeground(Color.WHITE);
        filterPanel.add(queryBtn);

        queryBtn.addActionListener(e -> {
            if(customerName.getText().isEmpty()){
                tradeInfoFind.setCustomerId(null);
            }else {
                tradeInfoFind.setCustomerId(customerName.getText());
            }
            tradeInfoFind.setTradeType(typeCombo.getSelectedItem().toString());
            Timestamp timestamp1 = new Timestamp(datePicker1.getDate().getTime());
            Timestamp timestamp2 = new Timestamp(datePicker2.getDate().getTime());
            tradeInfoFind.setTradeDate1(timestamp1);
            tradeInfoFind.setTradeDate2(timestamp2);

            List<TradeInfo> tradeInfos = adminDAO.getTradeInfoByCondition(tradeInfoFind);

            tradeInfoData.clear();
            tradeInfoData.addAll(tradeInfos);
            tableModel.fireTableDataChanged();


        });

        add(filterPanel, BorderLayout.NORTH);



        tradeInfoTable.setFont(new Font("宋体", Font.PLAIN, 14));
        tradeInfoTable.setRowHeight(30);
        tradeInfoTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));

        add(new JScrollPane(tradeInfoTable), BorderLayout.CENTER);

        // 底部按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JButton refreshButton = createStyledButton("刷新数据", Color.decode("#FF9800"));
        JButton exportButton = createStyledButton("导出记录", Color.decode("#4CAF50"));

        buttonPanel.add(refreshButton);
        buttonPanel.add(exportButton);

        // 添加按钮事件处理
        exportButton.addActionListener(this::exportDeposit);
        refreshButton.addActionListener(e -> refreshData());

        add(buttonPanel, BorderLayout.SOUTH);

    }


    public static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setPreferredSize(new Dimension(120, 40));
        return button;
    }

    private List<TradeInfo> fetchTradeInfoData() {
        List<TradeInfo> data = adminDAO.getAllTradeInfo();
        return data;
    }



    private void exportDeposit(ActionEvent e)  {
        // 导出数据操作
        exportToExcel(tradeInfoData,"C:/exports/example.xlsx");
    }

    private void refreshData() {
        tradeInfoData.clear();
        tradeInfoData.addAll(fetchTradeInfoData());
        tableModel.fireTableDataChanged();
        JOptionPane.showMessageDialog(this, "数据已刷新!", "成功", JOptionPane.INFORMATION_MESSAGE);
    }



    // 筛选交易信息类
    public class TradeInfoFind {
        String tradeType;
        String  customerId;
        Timestamp tradeDate1;
        Timestamp tradeDate2;

        public String getCustomerId() {
            return customerId;
        }

        public Date getTradeDate1() {
            return tradeDate1;
        }

        public Date getTradeDate2() {
            return tradeDate2;
        }

        public String getTradeType() {
            return tradeType;
        }


        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        public void setTradeDate1(Timestamp tradeDate1) {
            this.tradeDate1 = tradeDate1;
        }

        public void setTradeDate2(Timestamp tradeDate2) {
            this.tradeDate2 = tradeDate2;
        }

        public void setTradeType(String tradeType) {
            this.tradeType = tradeType;
        }

    }

    // 导出数据方法
    public void exportToExcel(List<TradeInfo> trades, String filePath) {

        // 确保目录存在
        File outputFile = new File(filePath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs();
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("交易数据");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"交易ID", "交易日期", "交易类型", "卡号", "金额", "备注"};
            for (int i = 0; i < headers.length; i++) {
                headerRow.createCell(i).setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (TradeInfo trade : trades) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(trade.getTradeId());
                row.createCell(1).setCellValue(trade.getTradeDate().toString());
                row.createCell(2).setCellValue(trade.getTradeType());
                row.createCell(3).setCellValue(trade.getCardId());
                row.createCell(4).setCellValue(trade.getTradeMoney().doubleValue());
                row.createCell(5).setCellValue(trade.getRemark());
            }

            // 写入文件
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
                System.out.println("文件已成功导出到: " + outputFile.getAbsolutePath());
            }
        }catch (Exception e) {
            System.err.println("导出失败: " + e.getMessage());
        }
    }
}


